#include "luster_fs.hh"

#include <stdio.h>

#include "luster_log.hh"
#include "luster_string.hh"
#include "luster_subproc.hh"
#include "luster_vec.hh"

namespace luster {

Status mkdir_all(char const *path) {
	// TODO: call libc functions instead of external program.
	Cmd cmd;

	cmd_append(&cmd, "mkdir");
	cmd_append(&cmd, "-p");
	cmd_append(&cmd, path);
	luster_TRY(cmd_run(&cmd));

	return STATUS_OK;
}

Status read_file(char const *path, StringBuffer *buf) {
	FILE *fp = fopen(path, "r");

	if (fp == NULL) {
		logprint(LOG_ERROR, "failed to open file: %s", path);
		return STATUS_ERROR;
	}

	fseek(fp, 0, SEEK_END);
	long n = ftell(fp);
	fseek(fp, 0, SEEK_SET);

	logprint(LOG_DEBUG, "read file, size: %ld", n);

	buf->chars_.len = 0;
	vec_reserve(&buf->chars_, n + 1);
	buf->chars_.len = n + 1;
	buf->chars_.data[n] = 0;

	fread(buf->chars_.data, n, 1, fp);

	if (ferror(fp)) {
		logprint(LOG_ERROR, "failed to read content of file: %s", path);
		return STATUS_ERROR;
	}

	return STATUS_OK;
}

} // namespace luster
